<template xmlns="http://www.w3.org/1999/html">
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="活动名称" prop="promotionName">
        <el-input
          v-model="queryParams.promotionName"
          placeholder="请输入活动名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="活动类型" prop="discountType">
        <el-select
          v-model="queryParams.discountType"
          placeholder="活动类型"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.mall_full_discount_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="state">
        <el-select
          v-model="queryParams.state"
          placeholder="状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.mall_promotion_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="活动时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="活动开始日期"
          end-placeholder="活动结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mall-manager:fullDiscount:add']"
        >新增</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="couponList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="活动名称" align="center" prop="promotionName" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180" />
      <el-table-column label="结束时间" align="center" prop="endTime" width="180" />
      <el-table-column label="活动类型" align="center" prop="discountType" width="180" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mall_full_discount_type" :value="scope.row.discountType"/>
        </template>


      </el-table-column>
      <el-table-column label="状态" align="center" prop="promotionStatus" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mall_promotion_state" :value="scope.row.promotionStatus"/>
        </template>

      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">


        <template slot-scope="scope">
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown" >
              <el-dropdown-item  v-hasPermi="['mall-manager:fullDiscount:query']">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-viewt"
                  @click="handleView(scope.row)"
                >查看</el-button>
              </el-dropdown-item>
              <el-dropdown-item  v-if="scope.row.isEnable == 0" v-hasPermi="['mall-manager:fullDiscount:edit']">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                >修改</el-button>
              </el-dropdown-item>
              <el-dropdown-item v-if="scope.row.isEnable == 0"  v-hasPermi="['mall-manager:fullDiscount:edit']">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-check"
                  @click="handleEnable(scope.row)"
                >启用</el-button>
              </el-dropdown-item>
              <el-dropdown-item v-hasPermi="['mall-manager:fullDiscount:edit']" v-if="scope.row.isEnable == 1 && (scope.row.promotionStatus === 'START' || scope.row.promotionStatus === 'NEW')">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-close"
                  @click="handleClose(scope.row)"
                >关闭</el-button>
              </el-dropdown-item>
              <el-dropdown-item command="a"  v-if="scope.row.isEnable == 0"   v-hasPermi="['mall-manager:fullDiscount:remove']">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                >删除</el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>

      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商城优惠券活动对话框 -->
    <el-dialog :title="title" :visible.sync="open" v-if="open" width="65%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="活动名称" prop="promotionName">
              <el-input v-model="form.promotionName" placeholder="请输入活动名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动时间" >
              <el-date-picker
                v-model="formDateRange"
                type="daterange"
                value-format="yyyy-MM-dd HH:mm:ss"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="30">
          <el-col :span="24">
            <el-form-item label="活动描述" prop="description">
              <el-input type="textarea"  :rows="4"   maxlength="100" show-word-limit v-model="form.description" placeholder="请输入活动描述" />
            </el-form-item>
          </el-col>
        </el-row>


        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="优惠门槛" prop="fullMoney">
              <el-input v-model="form.fullMoney" placeholder="请输入优惠门槛" >
                <template slot="append">元</template>
              </el-input>
              <span style="font-size: 12px">* 消费达到当前金额可以参与优惠</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优惠方式" prop="discountType">
              <el-radio-group v-model="form.discountType">
                <el-radio-button label="FULL_MINUS">满减</el-radio-button>
                <el-radio-button label="FULL_RATE">满折</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="优惠金额" prop="fullMoney" v-if="form.discountType == 'FULL_MINUS'">
              <el-input v-model="form.fullMinus" placeholder="请输入优惠金额" >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="优惠折扣" prop="fullRate" v-if="form.discountType == 'FULL_RATE'">
              <el-slider
                v-model="form.fullRate"
                :max="9.99"
                :min="0.01"
                :step="0.01"
                show-input>
              </el-slider>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="额外赠送" >
              <el-checkbox v-model="form.freeFreightFlag" :true-label="1" :false-label="0">免邮费</el-checkbox>
              <el-checkbox v-model="form.couponFlag" :true-label="1" :false-label="0">送优惠券</el-checkbox>
              <el-checkbox v-model="form.giftFlag" :true-label="1" :false-label="0">送赠品</el-checkbox>
              <el-checkbox v-model="form.pointFlag" :true-label="1" :false-label="0">送积分</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="赠送优惠券" prop="couponId" v-if="form.couponFlag == '1'">
              <span v-if="selectCouponList.length > 0"   style="margin-right: 20px;color: #6d6b6b">{{selectCouponList[0].promotionName}}</span>
              <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handCouponChoose"
            >选择</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="赠品" prop="fullRate" v-if="form.giftFlag == '1'">
              <span v-if="selectGiftList.length > 0"   style="margin-right: 20px;color: #6d6b6b">{{selectGiftList[0].goodsName}}</span>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handGiftChoose"
              >选择</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="赠积分" prop="fullRate" v-if="form.pointFlag == '1'">
              <el-input v-model="form.point" placeholder="请输入赠送积分" />
            </el-form-item>
          </el-col>

        </el-row>

        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="使用范围" prop="scopeType" >
              <el-radio-group v-model="form.scopeType">
                <el-radio-button label="ALL">全品类</el-radio-button>
                <el-radio-button label="PORTION_GOODS">指定商品</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>

        </el-row>


        <el-form-item  prop="scopeType" v-if="form.scopeType == 'PORTION_GOODS'">
          <div style="display: flex; margin-bottom: 10px">
            <el-button  type="primary" @click="openSkuList"
            >选择商品</el-button>

            <el-button
              type="error"
              ghost
              style="margin-left: 10px"
              @click="delSelectGoods"
            >批量删除</el-button
            >
          </div>
          <el-table  :data="promotionGoodsList" @selection-change="handleGoodsSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="商品名称" align="center" prop="goodsName" />
            <el-table-column label="商品价格" align="center" prop="price" />
            <el-table-column label="库存" align="center" prop="quantity" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="delGoods(scope.$index)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>






      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--  优惠券选择   -->
    <el-dialog title="选择优惠券" :visible.sync="couponopen" v-if="couponopen" width="80%" >
      <coupon-choose  :selectedWay="selectCouponList" :chooseType="couponChooseType" @selectedCouponData="selectedCoupon"></coupon-choose>
    </el-dialog>


    <!--  商品选择   -->
    <el-dialog title="商品选择" :visible.sync="goodsopen" v-if="goodsopen" width="65%" append-to-body>
      <goods-dialog :selectedWay="promotionGoodsList" @selectedGoodsData="selectedGoodsData" @closeGoodsData="closeGoodsData"></goods-dialog>
    </el-dialog>

    <!--  赠品选择   -->
    <el-dialog title="赠品选择" :visible.sync="giftopen" v-if="giftopen" width="65%" append-to-body>
      <goods-dialog :selectedWay="selectGiftList" :chooseType="giftChooseType" @selectedGoodsData="selectedGiftData" @closeGoodsData="closeGiftData"></goods-dialog>
    </el-dialog>

    <!--  优惠券查看   -->
    <el-dialog title="查看" :visible.sync="viewopen" v-if="viewopen" width="70%" append-to-body>
      <coupon-view :activityId="id"></coupon-view>
    </el-dialog>
  </div>
</template>

<script>
import {
  listFullDiscount,
  getFullDiscount,
  delCouponActivity,
  enableFullDiscount,
  addFullDiscount, updateFullDiscount, delFullDiscount
} from "@/api/mall/promotion/full-discount";
import CouponChoose from '@/views/mall/promotion/coupon/choose.vue'
import CouponView from './view'
import GoodsDialog from '@/views/mall/components/lili-dialog/goods-dialog'
export default {
  name: "FullDiscount",
  dicts: ['mall_full_discount_type','mall_coupon_activity_scope','mall_coupon_scope_type','mall_promotion_state'],
  components: {
    CouponView,CouponChoose,GoodsDialog
  },
  data() {
    return {
      couponChooseType: 'single',
      giftChooseType: 'single',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商城优惠券表格数据
      couponList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      viewopen: false,
      couponopen: false,
      goodsopen: false,
      giftopen: false,
      // 日期范围
      dateRange: [],
      formDateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        promotionName: null,
        startTime: null,
        endTime: null,
        state: null,
        discountType: null
      },
      // 表单参数
      form: {},
      scopeIdGoods: [],
      promotionGoodsList: [],
      selectedGoods: [],
      rangeTimeType: 1,
      catProps: {
        value: 'id',
        label: 'name'
      },
      // 表单校验
      rules: {
        promotionName: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 2, max: 20, message: '活动名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        fullMoney: [
          { required: true, message: "请输入优惠门槛", trigger: "blur" },
        ],
        discountType: [
          { required: true, message: "请选择优惠方式", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入活动范围描述", trigger: "blur" },
        ],
        consumeThreshold: [
          { required: true, message: "请输入消费门槛", trigger: "blur" },
        ],
        scopeType: [
          { required: true, message: "请选择使用范围", trigger: "blur" },
        ],
        rangeTime: [{ required: true, message: "请选择优惠券有效期" ,trigger: "blur"}],
      },
      id: null,
      selectCouponList: [], //选择的优惠券列表
      selectGiftList: [], //选择的赠品列表
      selectMemberList: [], //选择的会员列表
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询商城优惠券列表 */
    getList() {
      this.loading = true;
      if (this.dateRange.length > 0){
        this.queryParams.startTime = this.dateRange[0]
        this.queryParams.endTime = this.dateRange[1]
      }
      listFullDiscount(this.queryParams).then(response => {
        this.couponList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        promotionName: null,
        startTime: null,
        endTime: null,
        fullMoney: 1,
        discountType: 'FULL_MINUS',
        fullRate: 1,
        fullMinus: 1,
        freeFreightFlag: 0,
        couponFlag: 0,
        giftFlag: 0,
        pointFlag: 0,
        point: 0,
        giftId: null,
        couponId: null,
        scopeType: 'ALL',
      };
      this.resetForm("form");
      this.formDateRange = []
      this.selectCouponList = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商城满减活动";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getFullDiscount(id).then(response => {
        this.form = response.data.fullDiscount;
        this.formDateRange[0] = this.form.startTime
        this.formDateRange[1] = this.form.endTime

        this.promotionGoodsList = response.data.promotionGoodsList;

        if (this.form.couponFlag){
          this.selectCouponList = []
          this.selectCouponList.push(response.data.coupon)
        }

        if (this.form.giftFlag){
          this.selectGiftList = []
          this.selectGiftList.push(response.data.gift)
        }




        this.title = "修改商城满减活动";
        this.open = true;
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.viewopen = true;
      this.id = row.id
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.formDateRange.length < 1){
            this.$modal.msgError("请选择活动时间");
            return
          }else{
            this.form.startTime = this.formDateRange[0]
            this.form.endTime = this.formDateRange[1]
          }

          if (this.form.couponFlag == 1 && !this.form.couponId){
            this.$modal.msgError("请选择要赠送的优惠券");
            return;
          }

          if (this.form.giftFlag == 1 && !this.form.giftId){
            this.$modal.msgError("请选择要赠送的赠品");
            return;
          }

          if (this.form.pointFlag == 1 && !this.form.point && this.form.point < 1){
            this.$modal.msgError("请输入要赠送的积分");
            return;
          }


          if (this.form.scopeType === 'PORTION_GOODS'){
            if (this.promotionGoodsList.length < 1){
              this.$modal.msgError("请选择指定的商品");
              return;
            }
            this.form.promotionGoodsList = this.promotionGoodsList
          }
          if (this.form.id != null) {
            updateFullDiscount(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFullDiscount(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除？').then(function() {
        return delFullDiscount(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 启用按钮操作 */
    handleEnable(row) {
      const id = row.id ;
      this.$modal.confirm('是否确认启用？').then(function() {
        return enableFullDiscount(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },
    /** 关闭按钮操作 */
    handleClose(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认关闭？').then(function() {
        return closeCoupon(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },

    /* 选择优惠券*/
    handCouponChoose(){
      this.couponopen = true
    },
    /* 选择赠品*/
    handGiftChoose(){
      this.giftopen = true
    },
    /**
     * 返回优惠券*/
    selectedCoupon(val) {
      this.selectCouponList = []
      val.forEach((item) => {
        this.$set(item, 'num', 1)
        this.$set(item, 'couponId', item.id)

        let it = {
          ...item
        }
        this.selectCouponList.push(it)
      });
      this.form.couponId = this.selectCouponList[0].id
      this.couponopen = false
    },
    openSkuList() {
      // 显示商品选择器
      this.goodsopen = true;
      let data = JSON.parse(JSON.stringify(this.promotionGoodsList));
      data.forEach((e) => {
        e.id = e.skuId;
      });

    },
    closeGoodsData(){
      this.goodsopen = false
    },
    closeGiftData(){
      this.giftopen = false
    },
    selectedGoodsData(item) {
      // 回显已选商品
      let list = [];
      item.forEach((e) => {
        list.push({
          goodsName: e.goodsName,
          price: e.price,
          originalPrice: e.price,
          quantity: e.quantity,
          storeId: e.storeId,
          storeName: e.storeName,
          skuId: e.id,
          id: e.id,
          categoryPath: e.categoryPath,
          thumbnail: e.small,
          goodsType: e.goodsType,
          goodsId: e.goodsId,
          originPrice: e.price,
        });
      });
      this.promotionGoodsList = list;
      this.goodsopen = false
      console.log(JSON.stringify(this.promotionGoodsList))
    },
    selectedGiftData(item) {
      // 回显已选商品
      let list = [];
      item.forEach((e) => {
        list.push({
          goodsName: e.goodsName,
          price: e.price,
          originalPrice: e.price,
          quantity: e.quantity,
          storeId: e.storeId,
          storeName: e.storeName,
          skuId: e.id,
          id: e.id,
          categoryPath: e.categoryPath,
          thumbnail: e.small,
          goodsType: e.goodsType,
          goodsId: e.goodsId,
          originPrice: e.price,
        });
      });
      this.selectGiftList = list;
      this.form.giftId = this.selectGiftList[0].id
      this.giftopen = false
    },
    handleGoodsSelectionChange(selection){
      this.selectedGoods = selection
    },
    delSelectGoods() {
      let _this = this;
      // 多选删除商品
      if (this.selectedGoods.length <= 0) {
        this.$modal.msgError("您还未选择要删除的数据");
        return;
      }

      this.$modal.confirm('您确认要删除所选商品吗？').then(function() {
        let ids = [];
        _this.selectedGoods.forEach(function (e) {
          ids.push(e.id);
        });
        _this.promotionGoodsList = _this.promotionGoodsList.filter((item) => {
          return !ids.includes(item.id);
        });
      }).then(() => {
      }).catch((err) => {
        console.log("err:" + JSON.stringify(err))
      });
    },
    delGoods(index) {
      // 删除商品
      this.promotionGoodsList.splice(index, 1);
    },

  }
};
</script>
